<template>
  <div class="bgff p20">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="网关名">
        <el-select v-model="gatewayId" placeholder="请选择" @change="changeGate" style="width:150px;">
          <el-option
            v-for="item in gatewaylist"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备名">
        <el-select v-model="eqmtId" placeholder="请选择" style="width:150px;">
          <el-option v-for="item in eqmtList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          style="width:300px;"
          v-model="date"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" @click="search">查询</el-button>
        <el-button size="medium" type="primary" @click="reset">重置刷新</el-button>
        <!--<el-button size="medium" type="primary" @click="goShow">数据详情</el-button>-->
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      v-loading="loading"
      row-key="id"
      size="mini"
      border
      style="width: 100%;"
      class="mt20"
      empty-text="暂无数据"
    >
      <el-table-column
        type="index"
        width="50"
        :index="(index)=>{return (index+1) + (curPage - 1) * size }"
        label="序号"
      ></el-table-column>
      <el-table-column prop="a_i" label="电流（A）">
        <template slot-scope="scope">{{scope.row.a_i ? (scope.row.a_i/10).toFixed(1):'-'}}</template>
      </el-table-column>
      <el-table-column prop="a_di" label="剩余电流（mA）"></el-table-column>
      <el-table-column prop="a_v" label="电压（V）">
        <template slot-scope="scope">{{scope.row.a_v?scope.row.a_v/10:'-'}}</template>
      </el-table-column>
      <el-table-column prop="a_t" label="温度（℃）"></el-table-column>
       <el-table-column prop="createTime" label="采集时间">
        <template
          slot-scope="scope"
        >{{new Date(scope.row.create_time).format('yyyy-MM-dd hh:mm:ss')}}</template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt20"
      @current-change="handlePage"
      @size-change="handleSizeChange"
      :current-page.sync="curPage"
      :page-size="size"
      :page-sizes="[5,10,15,20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import {
  _historyList,
  _gatewaysAllGet,
  _excelData,
  _eqmtList
} from "@/http/ajax";
export default {
  data() {
    return {
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() > Date.now();
        }
      },
      loading: false,
      tableData: [],
      curPage: 1,
      size: 15,
      total: 0,
      date: [
        new Date(new Date().setDate(new Date().getDate() - 30)),
        new Date()
      ],
      gatewaylist: [],
      gatewayId: "",
      eqmtId: "",
      eqmtList: []
    };
  },
  created() {
    this.getGatewaysAll();
  },
  methods: {
    changeGate(val) {
      this.gatewaylist.forEach(el => {
        if (el.id === val) {
          // this.eqmtId = el.equipments[0].id;
          this.eqmtId = "";
          this.eqmtList = el.equipments;
        }
      });
    },
    // 获取所有网关
    getGatewaysAll() {
      let user = JSON.parse(sessionStorage.user);
      let data = {
        deptId: user.deptId || user.dept.id || "",
        level: sessionStorage.level
      };
      _gatewaysAllGet(
        data,
        res => {
          this.gatewaylist = res;
          let isFirst = true;
          if (this.gatewaylist.length) {
            this.gatewaylist.forEach(el => {
              if (el.equipments && el.equipments.length) {
                if (isFirst) {
                  this.gatewayId = el.id;
                  this.eqmtId = el.equipments[0].id;
                  this.eqmtList = el.equipments;
                  isFirst = false;
                }
                el["disabled"] = false;
              } else {
                el["disabled"] = true;
              }
            });
          } else {
            this.gatewayId = '';
          }
          this.getList();
        },
        err => {}
      );
    },
    search() {
       if(this.date){
        this.getList();
      }else{
        this.$message({
          message: "请选择时间范围",
          type: "error"
        });
      }
    },
    reset() {
      if(this.date){
         this.curPage = 1;
        this.gatewayId = "";
        this.size = 15;
        this.getList();
      }else{
        this.$message({
          message: "请选择时间范围",
          type: "error"
        });
      }
    },
    goShow() {
      let routeUrl = this.$router.resolve({
        path: `/eqmtShow/${this.eqmtId}`
        //   query: {id:row.id}
      });
      window.open(routeUrl.href, "_blank");
    },
    // 获取banner列表
    getList() {
      if(!this.eqmtId){
        this.$notify({
          title: "错误提示",
          message: "请选择设备",
          duration: 2000
        });
        return
      }
      let imei = '';
      this.eqmtList.forEach(el=>{
        if(el.id===this.eqmtId){
          imei = el.imeiTablename
        }
      })
      this.loading = true;
      this.tableData = [];
      let data = {
        page: this.curPage - 1,
        size: this.size,
        imei: imei,
        sort: "id,desc",
        startTime: this.date[0]
          ? new Date(this.date[0]).format("yyyy-MM-dd")
          : "",
        endTime: this.date[1] ? new Date(this.date[1]).format("yyyy-MM-dd") : ""
      };
      _historyList(
        data,
        res => {
          this.total = res.totalElements;
          this.tableData = res.content;
          this.loading = false;
        },
        err => {
          this.loading = false;
        }
      );
    },
    outExcel() {
      _excelData(
        {
          startTime: new Date(this.date[0]).format("yyyy-MM-dd"),
          endTime: new Date(this.date[1]).format("yyyy-MM-dd")
        },
        res => {
          this.excel(res.data);
        },
        err => {}
      );
    },
    //数据导出
    excel(data) {
      let html =
        '<tr  style="font-size:18px;font-weight:900;text-align:center">' +
        "<td>编号</td>" +
        "<td>接收号码</td>" +
        "<td>发送内容</td>" +
        "<td>发送时间</td>" +
        "<td>发送人</td>" +
        "<td>消息类型</td>" +
        "</tr>";
      for (let i = 0; i < data.length; i++) {
        html +=
          '<tr  style="font-size:14px;text-align:center">' +
          "<td>" +
          i +
          "</td>" +
          "<td>" +
          data[i].phone +
          "</td>" +
          "<td>" +
          data[i].text +
          "</td>" +
          "<td>" +
          new Date(data[i].create_at).format("yyyy-MM-dd hh:mm:ss") +
          "</td>" +
          "<td>" +
          data[i].username +
          "</td>" +
          "<td>通知</td>" +
          "</tr>";
      }
      let table = document.createElement("table");
      document.body.appendChild(table);
      table.style.display = "none";
      // table.style.borderCollapse='collapse';
      table.innerHTML = html;
      window.method5(table);
    },
    // 切换页码
    handlePage(val) {
      this.curPage = val;
      this.getList();
    },
    // 切换条数
    handleSizeChange(val) {
      this.size = val;
      this.getList();
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped></style>
